/*
 * Copyright 2010 Yaroslav Klymko aka t3hnar
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ua.t3hnar.io.serializer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ua.t3hnar.io.serializer.handlers.FieldHandler;
import ua.t3hnar.io.serializer.handlers.FieldHandlersProvider;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * @author Yaroslav Klymko aka t3hnar
 */
abstract class StreamFieldFinder {
// ------------------------------ FIELDS ------------------------------

    private static final Log LOG = LogFactory.getLog(StreamFieldFinder.class);
    private final SerializableFieldOwner owner;

// --------------------------- CONSTRUCTORS ---------------------------

    StreamFieldFinder(final SerializableFieldOwner owner) {
        if (owner == null) {
            throw new IllegalArgumentException();
        }
        this.owner = owner;
    }

// -------------------------- OTHER METHODS --------------------------

    void find() throws StreamSerializationException {
        LOG.debug("Finding");
        final Class<? extends SerializableFieldOwner> ownerClass = owner.getClass();
        final Field[] fields = ownerClass.getDeclaredFields();
        for (final Field field : fields) {
            final Class<SerializableField> annotationClass = SerializableField.class;
            final boolean isStatic = Modifier.isStatic(field.getModifiers());
            if (!isStatic && field.isAnnotationPresent(annotationClass)) {
                final SerializableField annotation = field.getAnnotation(annotationClass);
                final String key = annotation.handler();
                LOG.debug("Retrieving handler for key: " + key);
                final FieldHandler<?> handler = FieldHandlersProvider.getInstance().getHandler(key);
                LOG.debug("Retrieved handler: " + handler);
                final Class<?> type = field.getType();
                if (handler.isAssignable(type)) {
                    LOG.debug("Found: " + field);
                    found(this.owner, field, handler);
                }
            }
        }
    }

    abstract void found(final SerializableFieldOwner owner, final Field field, final FieldHandler handler) throws StreamSerializationException;
}
